<template>
  <view class="pay">
    <!-- 顶部head -->
    <view class="sun-header" :style="isSmallScreen ? 'height:94px;padding-top:95rpx':'‘'">
      <view class="sidebar" @click="openSidebar"></view>
      <image class="side" src="/static/images/icon/sidebar.png" @click="openSidebar" mode=""></image>
      <image class="logo" src="/static/images/icon/logo.png" mode=""></image>
      <image style="opacity: 0;" class="scan" src="/static/images/icon/scan.png" mode=""></image>
    </view>
    <!-- 金额 -->
    <view class="pay-money" :style="isSmallScreen ? 'height:84px':'‘'">
      <view class="symbol">$ </view>
      <view>{{ money | convertNum }}</view>
    </view>
    <!-- 金额键盘 -->
    <view class="keyboard">
      <view class="keyboard-item" :class="item == 'C' ? 'red' : ''" :style="'height:' + keyHeight + 'px'"
        v-for="(item, index) in keyList" :key="index" @touchend="updateMoney(item)">
        <span v-if="item != 'del'">{{ item }}</span>
        <image v-else src="/static/images/icon/del.png" mode="" style="width: 64rpx; height: 54rpx"></image>
      </view>
    </view>
    <!-- 支付方式 小屏幕 -->

    <view class="pay-type-samll" v-if="isSmallScreen">
      <view class="item" @click="openScan(DCS_CARD_NOW_PAY)">
        <!-- 大的按钮 -->
        <image class="big-image"
          :src="IS_DCS_CARD_NOW_PAY == false ? '/static/images/new-icon-1/Visa-master-dark.png' : '/static/images/new-icon-1/Visa-master.png'"
          mode="scaleToFill"></image>
      </view>
      <view class="item small-right">
        <view class="card" @click="openScan(ALI_MERCHANT_SCAN_USER_QR_PAY)">
          <image
            :src="IS_ALI_MERCHANT_SCAN_USER_QR_PAY == false ? '/static/images/new-icon-1/AliPay+-dark.png' : '/static/images/new-icon-1/AliPay+.png'"
            mode="scaleToFill"></image>
        </view>
        <view class="card" @click="openScan(GRAB_MERCHANT_PRESENTED_QR_PAY_LATER)">
          <image
            :src="IS_GRAB_MERCHANT_PRESENTED_QR_PAY_LATER == false ? '/static/images/new-icon-1/Grab-pay-dark.png' : '/static/images/new-icon-1/Grab-pay.png'"
            mode="scaleToFill"></image>
        </view>
        <view class="card" @click="openScan(WECHAT_MERCHANT_SCAN_USER_QR_PAY)">
          <image
            :src="IS_WECHAT_MERCHANT_SCAN_USER_QR_PAY == false ? '/static/images/new-icon-1/wechat-dark.png' : '/static/images/new-icon-1/wechat.png'"
            mode="scaleToFill"></image>
        </view>
        <view class="card" @click="openScan(DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY)">
          <image
            :src="IS_DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY == false ? '/static/images/new-icon-1/Paynow-dark.png' : '/static/images/new-icon-1/Paynow.png'"
            mode="scaleToFill"></image>
        </view>
      </view>
    </view>
    <!-- 支付方式 大屏幕-->
    <view class="pay-type" v-if="!isSmallScreen">
      <view @click="openScan(DCS_CARD_NOW_PAY)" class="item">
        <!-- 大的按钮 -->
        <image
          :src="IS_DCS_CARD_NOW_PAY == false ? '/static/images/new-icon/card-disabled.png' : '/static/images/new-icon/card.png'"
          mode="scaleToFill"></image>
      </view>
      <!-- 右侧固定两个 -->
      <view class="item-right">
        <view @click="openScan(ALI_MERCHANT_SCAN_USER_QR_PAY)" class="item">
          <image
            :src="IS_ALI_MERCHANT_SCAN_USER_QR_PAY == false ? '/static/images/new-icon/AliPay+-dark.png' : '/static/images/new-icon/AliPay+.png'"
            mode="scaleToFill"></image>
        </view>
        <view @click="openScan(GRAB_MERCHANT_PRESENTED_QR_PAY_LATER)" class="item">
          <image
            :src="IS_GRAB_MERCHANT_PRESENTED_QR_PAY_LATER == false ? '/static/images/new-icon/Grab-pay-dark.png' : '/static/images/new-icon/Grab-pay.png'"
            mode="scaleToFill"></image>
        </view>
      </view>
      <view @click="openScan(DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY)" class="item">
        <image
          :src="IS_DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY == false ? '/static/images/new-icon/Paynow-dark.png' : '/static/images/new-icon/Paynow.png'"
          mode="scaleToFill"></image>
      </view>

      <view @click="openScan(WECHAT_MERCHANT_SCAN_USER_QR_PAY)" class="item">
        <image
          :src="IS_WECHAT_MERCHANT_SCAN_USER_QR_PAY == false ? '/static/images/new-icon/wechat-dark.png' : '/static/images/new-icon/wechat.png'"
          mode="scaleToFill"></image>
      </view>

      <!-- 测试按钮 这里改个判断 -->
      <view @click="openScanTest(SOLANA_PAY)" class="item">
        <image
          :src="IS_SOLANA_PAY == false ? '/static/images/new-icon/upnetwork-disabled.png' : '/static/images/new-icon/upnetwork-1.png'"
          mode="scaleToFill"></image>
      </view>
    </view>
    <!-- 支付中 -->
    <view class="paying" v-if="showPaying">
      <view class="pay-mask"></view>
      <view class="pay-img" v-if="payTimeout == false">
        <image v-if="locale == 'en'" src="/static/images/pay/paying-en.png" mode="widthFix"></image>
        <image v-else src="/static/images/pay/paying-zh.png" mode="widthFix"></image>
      </view>
      <view class="pay-img" v-else @click="cli_clo_showPaying()">
        <image v-if="locale == 'en'" src="/static/images/pay/close-en.png" mode="widthFix"></image>
        <image v-else src="/static/images/pay/close-zh.png" mode="widthFix"></image>
      </view>
    </view>

    <!-- 失败弹框 -->
    <view class="paying" v-if="showErrorPay">
      <view class="pay-mask"></view>
      <view class="pay-img pay-con">
        <view class="pay-icon">
          <image src="/static/images/pay/error.png" mode="widthFix"></image>
        </view>
        <view class="pay-title">{{ $t('Error') }}</view>
        <view class="pay-desc">{{ errorPayDesc }}</view>
        <view class="pay-btn" @click="showErrorPay = false">{{
          $t('ErrorBtn')
        }}</view>
      </view>
    </view>

    <view class="head-card" v-if="is_dcs_show">
      <!-- <sun-header :title="$t('log.headTitle')"></sun-header> -->
      <view class="img">
        <image v-for="(item, index) in 5" :key="index" class="svg" v-if="index == money_type_icon"
          :src="`/static/images/headCard/hand-card-${index + 1}.svg`" mode="">
        </image>
      </view>
      <view class="t1">Total</view>
      <view class="t2"> S${{ money | convertNum }} </view>
      <view class="t3"> Tap, Insert, or Swipe to pay </view>
      <view class="footer-btn" @click="cancel_dcs"> Tap to cancel </view>
    </view>

    <!-- GrabPay 支付 -->
    <view class="grabPay" :style="'padding-top:'+grabPayPaddingTop+'px;'" v-show="showGrabPay">
      <view class="" v-if="locale == 'zh'">
        <view class="g-title">请使用支持该支付渠道的应用</view>
        <view class="g-title">扫描下方二维码并完成支付</view>
      </view>
      <view class="" style="width: 90%;margin: 0 auto;" v-else>
        <view class="g-title">Please scan the QR code with the relevant app to make the payment</view>
      </view>

      <view class="g-qr">
        <!-- <image class="g-scan" src="/static/images/pay/scan.png" mode="widthFix"></image> -->
        <uqrcode v-if="
            payMentType == 'GrabPay' || 
            payMentType == 'BTC_PAY' || 
            payMentType == 'SOLANA_PAY' || 
            payMentType == 'ETHEREUM_PAY'
          " ref="uqrcode" canvas-id="qrcode" :value="qr_url" :size="qrSize" :options="{ margin: 10 }"></uqrcode>
        <image v-else :style="'width: '+qrSize+'px; height: '+qrSize+'px'" class="g-scan"
          :src="'data:image/jpeg;base64,' + qr_url" mode="widthFix"></image>
      </view>
      <view class="g-status-image" v-if="locale == 'zh'">
        <image :style="'width:'+note_image_width+'%;'" class="note-image" src="/static/images/pay/note-CN.svg"
          mode="widthFix"></image>
      </view>
      <view class="g-status-image" v-else>
        <image :style="'width:'+note_image_width+'%;'" class="note-image" src="/static/images/pay/note-EN.svg"
          mode="widthFix"></image>
      </view>
      <view class="g-button" @click="hideQrcode">{{ $t('grab.b') }}</view>

      <view v-if="!isSmallScreen" class="bottom-logo">
        <image src="/static/images/login/bottom-logo.svg" mode=""></image>
      </view>
    </view>

    <!-- 侧边栏 -->
    <sidebar v-show="showSidebar" :version="versionCode" :status="showSidebar" @close="closeSidebar"></sidebar>
  </view>
</template>

<script>
  import sidebar from '@/components/sidebar/sidebar.vue'
  import api from '@/utils/api/index.js'
  import {
    refreshToken
  } from '@/config/config.js'
  import utils from '@/utils/util.js'
  import music from '@/utils/music/music.js'
  import sunHeader from '@/components/sun-header/sun-header.vue'
  const initSunmi = uni.requireNativePlugin('Hd-InitSunmiModule');
  const saleSm = uni.requireNativePlugin('Hd-SaleSmModule');
  const scanner = uni.requireNativePlugin('Ba-Scanner');
  const HceSunmi = uni.requireNativePlugin('HL-HceSunmiModule');
  
  export default {
    name: 'pay',
    components: {
      sidebar,
      sunHeader,
    },
    data() {
      return {
		timeout_time:800,
        bluetoothStatus: false,
        payStatusTimer: null,
        money: '0.00',
        // payTypeHeight: 80,
        keyHeight: 70,
        inputMoney: [],
        keyList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 'C', 0, 'del'],
        // 'GrabPay', 'AliPay+', 'wechat'
        payTypeList: [],
        showSidebar: false,

        systemInfo: '',
        showPaying: false,
        payTimeoutTemp: null, // 支付超时 定时器
        payTimeout: false,
        showErrorPay: false,
        errorPayDesc: '',

        iconRootPath: '/static/sj',
        wgtConfig: {}, // 升级配置
        locale: 'zh',
        description: '',
        isShowupgrade: false,
        pushClientid: '',

        versionCode: '100',
        showGrabPay: false,

        showOtherPay: false,
        //二维码相关参数
        modal_qr: false,
        qr_url_test: 'https://www.baidu.com/', // 要生成的二维码值
        qr_url: '', // 要生成的二维码值
        onlyContentId: '',

        payMentType: '',
        grabPayPaddingTop: 65,
        qrMb: 20,
        grabMb: 0,
        qrSize: 280,
        note_image_width: 100,

        transactionArr: [],
        windowWidth: 0,
        is_lunxun: 0,
        manual_key_btn: 'Manual Key',
        money_type_icon: 0, // 5个图片
        is_dcs_show: false,
        yi_dcs: null,
        uniWebOrderId: '',
        vMainData: {
          amount: 0,
          tips: 0,
          orderId: '',
          cardNo: '',
          cardExpDate: '',
          cardCvv: '',
        },
        
        dcs_base64: '',
        cryptoBtcAddress: '',
        cryptoSolanaAddress: '',
        cryptoEthereumAddress: '',
        DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY: {},
        WECHAT_MERCHANT_SCAN_USER_QR_PAY: {},
        ALI_MERCHANT_SCAN_USER_QR_PAY: {},
        GRAB_MERCHANT_PRESENTED_QR_PAY_LATER: {},
        DCS_CARD_NOW_PAY: {},
        SOLANA_PAY: {},
        IS_DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY: false,
        IS_WECHAT_MERCHANT_SCAN_USER_QR_PAY: false,
        IS_ALI_MERCHANT_SCAN_USER_QR_PAY: false,
        IS_GRAB_MERCHANT_PRESENTED_QR_PAY_LATER: false,
        IS_DCS_CARD_NOW_PAY: false,
        IS_SOLANA_PAY: false,

        ETHEREUM_PAY: {
          acquirerType: 'ETHEREUM_PAY'
        },
        SOLANA_PAY: {
          acquirerType: 'SOLANA_PAY'
        },
        BTC_PAY: {
          acquirerType: 'BTC_PAY'
        },

        // 是否小屏幕
        isSmallScreen: false,
        is_nfc: 0,
		is_nfc_write_success:0,
      }
    },
    filters: {
      convertNum(num) {
        if (num == '0.00') {
          return num
        }
        // 正则转换为千分位 1,234.56
        let n = num.replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
        return n
      },
    },
    onShow() {
      this.onInstall();
    },
    mounted() {
      let _this = this;
	  initSunmi.getSn((res) => {
		  if (res.code === 200) {
			let shebei = res.data;  
			  uni.setStorageSync('MOT-SUNMISN', shebei)
		  }else{
			  uni.setStorageSync('MOT-SUNMISN', '')
		  }
	  });
	  
      let systemInfo = uni.getSystemInfoSync('systemInfo');
      //systemInfo.deviceModel = "P3";
      if (systemInfo.deviceModel == "P2_SE") {
        _this.isSmallScreen = true;
        _this.qrSize = 200;
        _this.grabPayPaddingTop = 20;
        _this.note_image_width = 80;
      } else {
        _this.qrSize = 300;
        _this.grabPayPaddingTop = 65;
        _this.note_image_width = 100;
        _this.isSmallScreen = false;
      }

		let o = {terminalId:uni.getStorageSync('terminalId'),detail:JSON.stringify(uni.getSystemInfoSync('systemInfo'))};
		_this.$global.addLog(JSON.stringify(o), 'addSystemLog');
      // 测试
      /*
      let a =
        `eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJQMzAyUDQxTDEwMDc4IiwidGVybWluYWxEdG8iOiJ7XCJjcmVhdGlvblRpbWVcIjpcIjIwMjQtMDQtMDQgMTE6MTk6MzRcIixcImRlbGV0ZWRTdGF0dXNcIjpcIk5PXCIsXCJpZFwiOjEyMjU0MDQzOTE3MDA2OTI5OTIsXCJsYXN0QWN0aXZlVGltZVwiOlwiMjAyNC0wNC0wNCAxMToxOTozM1wiLFwibGFzdFVwZGF0ZVRpbWVcIjpcIjIwMjQtMTAtMjEgMDk6NDE6MjlcIixcIm93bmVyc2hpcFwiOlwiVGFuZ3MgVFBcIixcInNlcmlhbE51bWJlclwiOlwiUDMwMlA0MUwxMDA3OFwiLFwic3RvcmVJZFwiOjEwODAxNzIyODM2MzA1ODM4MDh9IiwibmJmIjoxNzI5NTA2MTA1LCJkZXZpY2VUb2tlbkR0byI6IntcImNyZWF0aW9uVGltZVwiOlwiMjAyNC0xMC0yMSAxODoxMzoxNFwiLFwiZGVsZXRlZFN0YXR1c1wiOlwiTk9cIixcImlkXCI6MTI5Nzk4NjA2OTkyNDU0NDUxMixcImxhc3RVcGRhdGVUaW1lXCI6XCIyMDI0LTEwLTIxIDE4OjEzOjE0XCIsXCJzdGF0dXNcIjpcIm5ld1wiLFwic3RvcmVJZFwiOjEwODAxNzIyODM2MzA1ODM4MDgsXCJ0b2tlblwiOlwiOVVFOTFBSkZFUFwifSIsInRlcm1pbmFsSWQiOiIxMjI1NDA0MzkxNzAwNjkyOTkyIiwiZXhwIjoyMDQ0ODY2MTA1fQ.nEj8KzINk9isERbm0NroE146XjxZ4Wz45THPCyQvivCSO9E1KXjIwczY7nfa2CUZbUkCPJ1Tzz2no9lUy6PTMQIjZLOZVI0YkPsQFGBAtNMGLCeB5Ghe59kdTTrspybqL1nOpiF9L7VRbPUcyC2IoJudKvwIygZmeuaA74i1u54DyBc5Fu2bEunzU40ug9fCHKbYuUj5VjOu59uQRowCjBWUDYw1DA47lM0r3bta0vjS-gtAwP_lo5lGxDe7GsVXKaw_-IbeuB6CHciJzRXHRjVkVxEmLdxoU8NkdhyrBNx2i_vXdwQCiI3DLb9ORfOTWVlLyIuoyvKqJ-MsB-Y_sQ`
      uni.setStorageSync('Authorization', a)
      uni.setStorageSync('terminalId', '1225404391700692992')
      //uni.setStorageSync('MOT-SUNMISN', 'P302P41L10078')
	  */
      let token = uni.getStorageSync('Authorization');
      let terminalId = uni.getStorageSync('terminalId');
      console.log(terminalId, 'terminalId');
      console.log(token);
      if (!token || !terminalId) {
        uni.reLaunch({
          url: '/pages/login/login',
        });
      } else {
        _this.getStoreName();
        _this.selectAcquirerStoreDtoWithAcquirer();
		_this.getCryptoData();
		
		HceSunmi.iniPaySDK();
		setTimeout(function() {
			HceSunmi.getSysParam("NFC", (result) => {
				console.log("is_nfc");
				console.log(result)
				if(result.data){
					if(result.data == "11"){
						_this.is_nfc = 1;
						_this.$global.addLog("is_nfc_success", 'is_nfc');
					}else{
						_this.$global.addLog("is_nfc_error_1", 'is_nfc');
					}
				}else{
					_this.$global.addLog("is_nfc_error_1", 'is_nfc');
				}
				//{"data": "11","message": "success","code": 200}
			});
		},1000);
      }
    },
    methods: {
		async getStoreName() {
			let res = await api.storeInfo({})
			if (res.code == '000000') {
				let data = res.data;
				uni.setStorageSync('storeName', data.name)
			}
		},
		async getCryptoData() {
			let _this = this;
			let res = await api.getCryptoData({});
			if (res.code == '000000') {
				_this.cryptoBtcAddress = res.data.cryptoBtcAddress;
				_this.cryptoSolanaAddress = res.data.cryptoSolanaAddress;
				_this.cryptoEthereumAddress = res.data.cryptoEthereumAddress;
			}
		},
      selectStoreDcsConfigurationList() {
        let _this = this;
        let o = {serialNumber: uni.getStorageSync('MOT-SUNMISN')};
        _this.$global.addLog(JSON.stringify(o))
        console.log(o);
        api.selectStoreDcsConfigurationList(o).then((store) => {
          _this.$global.addLog(JSON.stringify(store),'selectStoreDcsConfigurationList');
          console.log(store);
          console.log('***************');

          if (store.code == '000000') {
            this.storeInfo = store.data
            uni.setStorageSync('storeInfo', store.data)
            initSunmi.initSdk('702', '702', (result) => {
              console.log('init==========init');
              console.log(result);
              console.log('init==========init');
              _this.$global.addLog(JSON.stringify(result), 'shangmi_init');
            });
          } else {
            if (store.code == 500002) {
              uni.removeStorageSync('terminalId')
              uni.removeStorageSync('Authorization')
              uni.reLaunch({
                url: '/pages/login/login',
              })
            } else {
              uni.showModal({
                title: '温馨提示',
                content: store.message,
                showCancel: false,
              })
            }
          }
        });
      },
      // 刷卡功能实现
      async paymentCard() {
        let _this = this;
        this.vMainData.amount = 0
        this.vMainData.tips = 0
        this.vMainData.orderId = ''
        this.vMainData.cardNo = ''
        this.vMainData.cardExpDate = ''
        this.vMainData.cardCvv = ''
        this.uniWebOrderId = ''
        if (this.money == '0.00') {
          utils.showText('金额不能为零');
          return;
        }
        saleSm.cancelCheckCard();
        this.acquirerType = 'DCS_CARD_NOW_PAY';
        this.is_dcs_show = true;
        this.yi_dcs = null;
        let i = 0;
        //图片轮播
        this.yi_dcs = setInterval(() => {
          this.money_type_icon = i;
          i++;
          if (i > 4) {
            i = 0;
          }
        }, 2000);
        let o = {
          acquirerType: 'DCS_CARD_NOW_PAY',
          paymentTerminalRequestVo: {
            amount: (this.money * 100).toFixed(0),
            currency: 'SGD',
            actionType: 'PAY',
          },
        }
        let res = await api.paymentPay(o)
        _this.$global.addLog(JSON.stringify(res), 'paymentPay')
        if (res.code == '000000') {
          //this.vMainData.orderId = res.data.transactionId
          this.uniWebOrderId = res.data.transactionId;
          this.vMainData.amount = (this.money * 100).toFixed(0);
          this.startSale();
        } else {
          this.cancel_dcs();
        }
      },
      /**
       * startSale
       */
      startSale() {
        let _this = this
        //let storeInfo = uni.getStorageSync('storeInfo');
        try {
          saleSm.startSale(this.vMainData, (result) => {
            _this.$global.addLog(JSON.stringify(result), 'startSale')
            if (result['code'] == -100002) {
              const merchantParams = {
                merchantId: this.storeInfo.dcsMerchantId, // 默认值  肯定DCS
                terminalId: this.storeInfo.dcsTerminalId, // 默认值  肯定DCS
                subMerchantCity: this.storeInfo.dcsSubMerchantCity,
                subMerchantId: this.storeInfo.dcsSubMerchantId,
                subTerminalId: this.storeInfo.dcsSubTerminalId,
                subMerchantName: this.storeInfo.dcsSubMerchantName,
                subMerchantCountryCode: this.storeInfo.dcsSubMerchantCountryCode,
              }
              _this.$global.addLog(JSON.stringify(merchantParams), 'merchantParams');
              initSunmi.setConfig(merchantParams, (config) => {
                console.log('config==========config')
                console.log(config)
                if (config.code == 200) {
                  _this.$global.addLog(JSON.stringify(config), 'config')
                  initSunmi.signOn((sign) => {
                    console.log('signOn==========signOn')
                    console.log(sign)
                    _this.$global.addLog(JSON.stringify(sign), 'signOn')
                    if (sign.code == 200) {
                      _this.startSale()
                    } else {
                      //initSunmi.clearAllDBData();
                      this.cancel_dcs();
                      uni.showModal({
                        title: '温馨提示',
                        content: sign.data,
                        showCancel: false,
                      })
                    }
                  })
                } else {
                  this.cancel_dcs();
                  uni.showModal({
                    title: '温馨提示',
                    content: sign.data,
                    showCancel: false,
                  })
                }
              })
            } else if (result['code'] == -100003) {
              initSunmi.signOn((sign) => {
                console.log('signOn==========signOn')
                console.log(sign)
                _this.$global.addLog(JSON.stringify(sign), 'signOn')
                if (sign.code == 200) {
                  _this.startSale()
                } else {
                  //initSunmi.clearAllDBData();
                  this.cancel_dcs();
                  uni.showModal({
                    title: '温馨提示',
                    content: sign.data,
                    showCancel: false,
                  })
                }
              })
            } else {
              console.log(JSON.stringify(result) + 'startSale')
              console.log('~~~~~~~~~~~~~')
              let rdata = result['data']
              if (
                (result['code'] === 201 && rdata.cardNo) ||
                (result['code'] === 202 && rdata.uuid) ||
                (result['code'] === 203 && rdata.uuid)
              ) {
                this.setManualKey()
              } else {
                uni.showModal({
                  title: '温馨提示',
                  content: rdata,
                  showCancel: false,
                })
              }
            }
          })
        } catch (e) {
          this.cancel_dcs();
        }
      },
      /**
       * setManualKey
       */
      setManualKey() {
        let _this = this
        try {
          saleSm.setManualKey(_this.vMainData, (result) => {
            _this.$global.addLog(JSON.stringify(result), 'setManualKey');
            console.log(JSON.stringify(result) + 'setManualKey');
            let rdata = result['data'];
            if (result.code == '204' && result.message == 'onAppFinalSelect') {
              saleSm.confirmAppFinalSelect(true);
            } else if (result.code == '204' && result.message == 'onConfirmCardNo') {
              saleSm.confirmCardNo(true);
            } else {
              if (result.code == '201' && result.message == 'handle') { //wait or error

              } else if (result.code == '205' && result.message == 'trasnactionResult') {
                if (result.code == '205' && rdata.status == 'success' && rdata.result && rdata.result.answerCode ==
                  '00') {
                  setTimeout(function() {
                    utils.showLoading();
					saleSm.cardOff();
                    _this.paySuccess(rdata);
                  }, 500);
                } else {
                  _this.$global.addLog(JSON.stringify(result), 'setManualKey_error');
                  _this.cancel_dcs();
                  _this.shibao_tiao(rdata.sale);
                }
              } else {
                _this.$global.addLog(JSON.stringify(result), 'setManualKey_error');
                _this.cancel_dcs();
                let d_str = JSON.stringify(rdata);
                if (d_str.indexOf("4:") >= 0) {
                  _this.shibao_tiao(
                    'Please place the card in the designated area until the transaction is completed.');
                } else {
                  _this.shibao_tiao(rdata);
                }
              }

            }

          });
        } catch (e) {
          _this.cancel_dcs();
        }
      },

      paySuccess(data) {
        let _this = this
        try {
          _this.$global.addLog(JSON.stringify(data), 'paySuccess')
          let store = uni.getStorageSync('storeInfo') || {}
          if (data.sale) {
            uni.hideLoading()
            _this.$global.addLog(JSON.stringify(data))
            uni.showModal({
              title: '温馨提示',
              content: data.sale,
              showCancel: false,
            })
          } else {
            if (data.result.referenceNo) {
              let stan = data.result.stan
              let referenceNo = data.result.referenceNo
              let paymentMethodNext = data.paymentMethodNext
              let paymentMethod = data.result.paymentMethod //10501
              let paymentMethod_zhuan = paymentMethodNext.toUpperCase() + '_CARD'
              if (paymentMethod_zhuan == 'MASTERCARD_CARD') {
                paymentMethod_zhuan = 'MASTER_CARD'
              } else if (paymentMethod_zhuan == 'UNIONPAY_CARD') {
                paymentMethod_zhuan = 'UNION_PAY_CARD'
              }
              console.log(paymentMethod_zhuan + '============')

              let cardType = ''
              if (data.result.cardType == 1) {
                cardType = 'chip_swipe'
              } else if (data.result.cardType == 2) {
                cardType = 'stripe_insert'
              } else if (data.result.cardType == 3) {
                cardType = 'contactless_nfc'
              } else {
                cardType = 'manual'
              }
              let o = {
                cardPayWay: cardType,
                transactionId: _this.uniWebOrderId,
                transactionType: data.result.transactionType,
                cardNumber: data.result.cardNo,
                dcsPaymentMethod: paymentMethod_zhuan,
                paymentStatus: 'success',
                errorMessage: '',
                terminalStan: stan,
                acquirerTransactionId: referenceNo,
                cardCountry: data.result.issuerCode,
                mid: data.result.mid,
                tid: data.result.tid,
                stan: data.result.stan,
                exp: data.result.expDate,
                rrn: data.result.referenceNo,
                batch: data.result.batchNo,
                invoice: data.result.traceNo,
                trace: data.result.traceNo,
                apprCode: data.result.authNo,
                aid: data.result.aid,
                app: data.result.appName,
                tc: data.result.tc,
              }
              if (data.result.isLocal) {
                o.cardBelong = data.result.isLocal
              }

              _this.$global.addLog(
                JSON.stringify(o),
                'updateDcsCardPayTransaction'
              )
              console.log('============')
              console.log(o)
              console.log('============')
              api.updateDcsCardPayTransaction(o).then((res) => {
                _this.$global.addLog(
                  JSON.stringify(res),
                  'updateDcsCardPayTransaction_res'
                )
                if (res.code == '000000') {
                  _this.getPayStatusByWx(_this.uniWebOrderId);
                } else {
                  uni.hideLoading()
                  uni.showModal({
                    title: '温馨提示',
                    content: 'error',
                    showCancel: false,
                  })
                }
              })
            } else {
              uni.hideLoading()
              uni.showModal({
                title: '温馨提示',
                content: '交易失败',
                showCancel: false,
              })
            }
          }
        } catch (e) {
          //TODO handle the exception
          uni.hideLoading()
        }
      },
      cancel_dcs() {
		this.cli_clo_luxun();
        clearInterval(this.yi_dcs);
        this.yi_dcs = null;
        this.is_dcs_show = false;
        saleSm.cancelCheckCard();
      },
		onInstall() {
        let _this = this

        plus.runtime.setBadgeNumber(0)
        plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
          console.log(widgetInfo, '设备信息', _this.pushClientid)
          uni.setStorageSync('version', widgetInfo.version)
          let versionCode = widgetInfo.versionCode
          _this.versionCode = versionCode
        })
      },
      hideQrcode() {
		  let _this = this;
        _this.showGrabPay = false;
		_this.cli_clo_luxun();
        //clearInterval(this.payStatusTimer);
        //this.payStatusTimer = null;
        //this.is_lunxun = 0;
        _this.qr_url = '';
		if(_this.is_nfc == 1 && _this.is_nfc_write_success == 1){
			HceSunmi.writeNdefData("empty", (rr) => {
			   if(rr.message == "success" && rr.code == 200){
				   _this.is_nfc_write_success = 0;
					HceSunmi.closeHce();
			   }
			});
		}
      },
	  
      async selectAcquirerStoreDtoWithAcquirer() {
        let _this = this
        let res = await api.selectAcquirerStoreDtoWithAcquirer()
        console.log(res)
        console.log('zzzzzzzzzzzzzz')
        if (res.code == '000000') {
          _this.$global.addLog(
            JSON.stringify(res),
            'selectAcquirerStoreDtoWithAcquirer'
          )
          // GRAB_MERCHANT_PRESENTED_QR_GRAB_PAY GRAB_MERCHANT_PRESENTED_QR_PAY_LATER
          // 进行数据处理；如果 acquirerType == GRAB_MERCHANT_PRESENTED_QR_PAY_LATER 或者 acquirerType == GRAB_MERCHANT_PRESENTED_QR_GRAB_PAY 只显示 GrabPay
          // 1、重新赋值acquirerType
		  let list = res.data.map((a) => {
		    if (a.acquirerType == 'DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY') {
		      _this.DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY = a;
		      _this.IS_DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY = true;
		    } else if (a.acquirerType == 'WECHAT_MERCHANT_SCAN_USER_QR_PAY') {
		      _this.WECHAT_MERCHANT_SCAN_USER_QR_PAY = a;
		      _this.IS_WECHAT_MERCHANT_SCAN_USER_QR_PAY = true;
		    } else if (a.acquirerType == 'ALI_MERCHANT_SCAN_USER_QR_PAY') {
		      _this.ALI_MERCHANT_SCAN_USER_QR_PAY = a;
		      _this.IS_ALI_MERCHANT_SCAN_USER_QR_PAY = true;
		    } else if (a.acquirerType == 'GRAB_MERCHANT_PRESENTED_QR_PAY_LATER' || a.acquirerType == 'GRAB_MERCHANT_PRESENTED_QR_GRAB_PAY') {
		      _this.GRAB_MERCHANT_PRESENTED_QR_PAY_LATER = a;
		      _this.IS_GRAB_MERCHANT_PRESENTED_QR_PAY_LATER = true;
		    } else if (a.acquirerType == 'DCS_CARD_NOW_PAY') {
				if(_this.IS_DCS_CARD_NOW_PAY == false){
					_this.selectStoreDcsConfigurationList();			  
				}
				
		      _this.DCS_CARD_NOW_PAY = a;
		      _this.IS_DCS_CARD_NOW_PAY = true;
			  
		    } else if (a.acquirerType == 'SOLANA_PAY') {
		      _this.SOLANA_PAY = a;
		      _this.IS_SOLANA_PAY = true;
		    }
		    return a;
		  });
          setTimeout(() => {
            this.handleStyle(5)
          }, 0)
        }
      },
      // 处理样式
      handleStyle(len) {
        uni.getSystemInfo({
          success: (res) => {
            // 获取 .pay-type 的高度
            if (this.isSmallScreen) {
              const query = uni.createSelectorQuery().in(this)
              query
                .select('.pay-type-samll')
                .boundingClientRect((data) => {
                  if (data) {
                    // data.height 就是元素的高度
                    console.log('元素高度:', data.height)
                    // 109 + 95
                    let _h = 190 + data.height
                    let winH = res.screenHeight
                    this.keyHeight = (winH - _h) / 4
                  }
                })
                .exec()
            } else {
              const query = uni.createSelectorQuery().in(this)
              query
                .select('.pay-type')
                .boundingClientRect((data) => {
                  if (data) {
                    // data.height 就是元素的高度
                    console.log('元素高度:', data.height)
                    // 109 + 95
                    let _h = 240 + data.height
                    let winH = res.screenHeight
                    this.keyHeight = (winH - _h) / 4
                  }
                })
                .exec()
            }
          },
        })
      },
      updateMoney(item) {
        //console.log(item);
        // console.log(this.replayAcquireType('DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY'),'123')
        // 例如依次输入123：输入1 == 0.01，继续输入2 == 0.12 ，随后输入3应该进位变为 3 == 1.23 。
        // console.log(this.inputMoney)
        if (item == 'del') {
          music.click()
          // 删除的时候，逆向删除
          this.inputMoney.pop()
          this.money = this.inputMoney.join('')
          if (this.money.length == 0) {
            this.money = '0.00'
          } else if (this.money.length == 1) {
            this.money = '0.0' + this.money
          } else if (this.money.length == 2) {
            this.money = '0.' + this.money
          } else {
            this.money = this.money.slice(0, -2) + '.' + this.money.slice(-2)
          }
        } else if (item == 'C') {
          music.click()
          this.money = '0.00'
          this.inputMoney = []
        } else {
          //console.log(this.inputMoney.length, 'inputMoney')
          if (item == '0' && this.inputMoney.length == 0) {
            return
          }
          if (this.inputMoney.length > 7) {
            return
          }
          music.click()
          this.inputMoney.push(item)
          this.money = this.inputMoney.join('')
          if (this.money.length == 1) {
            this.money = '0.0' + this.money
          } else if (this.money.length == 2) {
            this.money = '0.' + this.money
          } else {
            this.money = this.money.slice(0, -2) + '.' + this.money.slice(-2)
          }
        }
      },
      async openScanTest(item) {
        let _this = this;
        if (_this.IS_SOLANA_PAY == false) {
          return;
        }
        if (_this.money == '0.00') {
          utils.showText('金额不能为零');
          return;
        }
		_this.locale = uni.getStorageSync('locale');	
        utils.showLoading();
        let o = {
          acquirerType: item.acquirerType,
          paymentTerminalRequestVo: {
            amount: (_this.money * 100).toFixed(0),
            currency: 'SGD',
            actionType: 'PAY',
            qrCodeNumber: ''

          }
        }
        console.log(o)
        let res = await api.paymentPay(o);
        if (res.code == '000000') {
          let data = res.data;
          _this.qr_url = data.transactionId;
          _this.payMentType = item.acquirerType;
          _this.showGrabPay = true;
          _this.getPayStatusByWx(data.transactionId);
		  console.log(_this.is_nfc+"===="+data.transactionId);
		  if(_this.is_nfc == 1){
			HceSunmi.openHce("Type4", (r) => {
				console.log("nfc is open");
				console.log(r);
			  if(r.message == "success" && r.code == 200){
				
				_this.$global.addLog("is_nfc_open_success", 'is_nfc');
				setTimeout(function() {
					HceSunmi.writeNdefData(data.transactionId, (rr) => {
					   console.log(rr);
					   if(rr.message == "success" && rr.code == 200){
							_this.is_nfc_write_success = 1;
					   }
					});
				},1000);
			  }else{
				_this.$global.addLog("is_nfc_open_error", 'is_nfc');
			  }
			});
		   
		  }
        }
        uni.hideLoading();
      },
      async openScan(item) {
        if (!item.acquirerType) {
          return false;
        }
        this.acquirerType = item.acquirerType;
        if (this.acquirerType == 'RED_DOT_PAY') {
          return;
        }

        this.locale = uni.getStorageSync('locale');
        if (this.acquirerType == 'ETHEREUM_PAY' || this.acquirerType == 'SOLANA_PAY' || this.acquirerType ==
          'BTC_PAY') {

        } else {
          if (this.money != '0.00') {
            if (this.acquirerType == 'DCS_CARD_NOW_PAY') {
              this.paymentCard();
            } else {
              let arr = [
                'GRAB_MERCHANT_PRESENTED_QR_GRAB_PAY',
                'GRAB_MERCHANT_PRESENTED_QR_PAY_LATER',
                'DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY',
              ];
              if (arr.includes(this.acquirerType)) {
                this.sendPayment('', item);
                return;
              }
              
			scanner.onScan({
				isShowBeep: true,
				hintText: '请对准二扫码',
				isShowToast: false,
				barcodeFormats: ['QR Code'],
			  },
			  (ret) => {
				console.log(ret);
				if (ret.result) {
				  this.sendPayment(ret.result, item);
				  scanner.onClose();
				}
			  }
			)
              
            }
          } else {
            utils.showText('金额不能为零');
          }
        }
      },
      // 发起支付
      async sendPayment(code, item) {
		let _this = this;
        utils.showLoading();
        let acquirerType = item.acquirerType
        let arr = [
          'GRAB_MERCHANT_PRESENTED_QR_GRAB_PAY',
          'GRAB_MERCHANT_PRESENTED_QR_PAY_LATER',
        ]
        if (arr.includes(acquirerType)) {
          acquirerType = 'GRAB_MERCHANT_PRESENTED_QR_PAY_LATER'
        }
		
		if (code) {//wechat or ali_pay
			_this.showPaying = true;
			_this.payTimeout = false;
			
			_this.payTimeoutTemp = setInterval(() => {
			  if(_this.showPaying == true){
			  	console.log("hhhhhhhhh")
			  	_this.payTimeout = true;
			  }else{
				  clearInterval(_this.payTimeoutTemp);
				  _this.payTimeoutTemp = null;
			  }
			}, 15000);
			
		}
        console.log(acquirerType, '支付方式')
        let o = {
          acquirerType: acquirerType,
          paymentTerminalRequestVo: {
            amount: (_this.money * 100).toFixed(0),
            currency: item.storeCurrency,
            actionType: 'PAY',
            qrCodeNumber: code,
          },
        }
        console.log('uuuuuuuuu')
        console.log(o)

        let res = await api.paymentPay(o)
        console.log(res, 'sss')
        if (res.code == '000000' || res.code == 'PAYMENT_IN_PROCESS') {
          let data = res.data;
          if (acquirerType == 'GRAB_MERCHANT_PRESENTED_QR_PAY_LATER') {
            _this.qr_url = data.grabPayLaterPaymentDto.qrcode
            _this.payMentType = 'GrabPay'
            _this.showGrabPay = true
            _this.getPayStatusByWx(data.transactionId)
            return
          } else if (acquirerType == 'DBS_PAY_NOW_MERCHANT_PRESENTED_QR_PAY') {
            _this.qr_url = data.dbsPayNowPaymentDto.base64Image
            _this.payMentType = 'PayNow'
            _this.showGrabPay = true
            _this.getPayStatusByWx(data.transactionId)
            return
          }

          _this.getPayStatusByWx(data.transactionId)
        } else if (res.code == 'PAYMENT_IN_PROCESS') {
          // 等待
        } else { //失败
          _this.shibao_tiao(res.message);
        }
        uni.hideLoading()
      },
	  cli_clo_showPaying(){
		  let _this = this;
		  _this.is_lunxun = 0;
		  _this.showPaying = false;
		  _this.payTimeout = false;
		  clearInterval(_this.payTimeoutTemp);
		  _this.payTimeoutTemp = null;
	  },
      // 每隔n秒请求一次接口api.selectTransactionById
      getPayStatusByWx(id) {
        let _this = this;
		_this.is_lunxun = 1;
	    _this.get_selectTransactionById(id);
      },
	  get_selectTransactionById(id) {
	    let _this = this;
		if(_this.is_lunxun == 0){
			return false;
		}
	    api.selectTransactionById({id:id}).then((res) => {
	      if (res.code == '000000') {
	        let data = res.data;
	        if (data.paymentStatus == "success") {
	          //clearInterval(_this.payStatusTimer);
	          _this.$global.addLog(JSON.stringify(res), 'startPrint');
	          if (data.acquirerType == "SOLANA_PAY") {
				
				_this.cli_clo_luxun();
	            _this.success_url(data);
	          } else if (data.acquirerType == "DCS_CARD_NOW_PAY") {
	            _this.success_url(data);
	            _this.cancel_dcs();
	          } else {
				_this.cli_clo_luxun();
	            _this.success_url(data);
	  
	          }
	        } else {
	          _this.$global.addLog(JSON.stringify(res), 'startPrint_wait');
			  _this.payStatusTimer = setTimeout(() => {
			    _this.get_selectTransactionById(id);
			  }, _this.timeout_time);
	        }
	      } else {
	        _this.$global.addLog(JSON.stringify(res), 'startPrint_wait');
			_this.payStatusTimer = setTimeout(() => {
			  _this.get_selectTransactionById(id);
			}, _this.timeout_time);
	      }
	      //_this.is_lunxun = 0
	      console.log('接口返回成功！！！');
		  
	    }).catch(() => {
	      console.log('接口异常重置成功！！！');
	      //_this.is_lunxun = 0;
	      _this.$global.addLog("yichang_error", 'startPrint_error');
		  _this.payStatusTimer = setTimeout(() => {
		    _this.get_selectTransactionById(id);
		  }, _this.timeout_time);
		  
	    });
	  },
		cli_clo_luxun(){
			let _this = this;
			_this.payStatusTimer = null;
			clearTimeout(_this.payStatusTimer);
			_this.is_lunxun = 0;
		},
      success_url(data) {
        let _this = this;
        //_this.payStatusTimer = null;
        _this.showPaying = false;
        _this.showGrabPay = false;
		_this.payTimeout = false;
		_this.qr_url = '';
		clearInterval(_this.payTimeoutTemp);
		_this.payTimeoutTemp = null;
		_this.money = '0.00';
		_this.inputMoney = [];
		music.success();
		
		if(_this.is_nfc == 1 && _this.is_nfc_write_success == 1){
			console.log("is_nfc_go_write");
			HceSunmi.writeNdefData("empty", (rr) => {
				console.log(rr);
			   if(rr.message == "success" && rr.code == 200){
				   _this.is_nfc_write_success = 0;
					HceSunmi.closeHce();
			   }
			});
		}
        uni.navigateTo({
          url: '/pages/paymentHistory/detail/detail?type=pay&id=' + data.id,
        });
    
      },
      shibao_tiao(msg) {
        this.showPaying = false;
        this.showErrorPay = false;

        uni.navigateTo({
          url: '/pages/status/status?type=2&num=0&id=' + msg,
        });
      },
      // 打开侧边个人中心
      openSidebar() {
        this.showSidebar = true
      },
      closeSidebar() {
        this.showSidebar = false
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import 'pay.scss';
</style>